#!/usr/bin/env python
#coding=utf-8
            
import logging, traceback
from tornado.escape import json_encode, json_decode

import log
import util
from util import ConfigManager
import const
from mysqlHelper import mysql
import time
import datetime
from store import store
import user
from user import *
import copy

logger = logging.getLogger(__name__)
 
#--------
def _decodeRowItem(row, name):
    if row[name]:
            row[name] = json_decode(row[name])
    else:
        row[name] = {}
    
def method_sys_login(request, data):  
    '''用户登录'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_sys_login exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = 'sys_login'
    
    data_dict = util.jsonDecode(data)
    name = data_dict.get('name')
    pwd = data_dict.get('pwd')
    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    conn = mysql()
    sql = "SELECT a.*,b.* FROM t_user a , t_user_data b WHERE  a.uid = b.uid AND name='%s' " % conn.escape_string(name)
    row = conn.getRow(sql)
    log.print_debug(logger, "method_sys_login exec, [-1]========[SELECT end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time())) 
    
    if row:
        del row['b.uid']
        del row['b.nickname']
        
        log.print_debug(logger, "method_sys_login exec, [0]========[kill_user_after_clear_info_Ext before], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time())) 
        
        uid = row['uid']
        user.UserManager.kill_user_after_clear_info_Ext(uid, True) #踢出同名用户
        
        log.print_debug(logger, "method_sys_login exec, [1]========[kill_user_after_clear_info_Ext end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))
        
        row['birthday'] = str(row['birthday'])
        row['age']=user.UserManager.countAge(row['birthday'])
        row['regtime'] = str(row['regtime'])
        row['upload_head_time'] = str(row['upload_head_time'])
        row['last_login_time'] = str(row['last_login_time'])    
        #row['autoinfo'] = str(row['autoinfo'])
        _decodeRowItem(row, 'reg_step')
        _decodeRowItem(row, 'my_clothing')
        _decodeRowItem(row, 'my_ornament')
        _decodeRowItem(row, 'my_present')
        _decodeRowItem(row, 'my_furniture')
        _decodeRowItem(row, 'my_props')
        _decodeRowItem(row, 'my_props_using')
        _decodeRowItem(row, 'my_bodyinfo')
        _decodeRowItem(row, 'autoinfo')
        _decodeRowItem(row, 'remark_info')        
        
        log.print_debug(logger, "method_sys_login exec, [2]========[add_user before], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))
        
        userinfo = row.copy()
    
        tmpUser = user.UserManager.add_user(userinfo, request)      #添加用户到内存队列
        
        log.print_debug(logger, "method_sys_login exec, [3]========[add_user end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))
        
        #---删除过期的"正在使用"的道具, 然后保存到DB
        from props_manager import PropManager
        PropManager.instance().delMyUsingPropsForOutTime(tmpUser)
        
        log.print_debug(logger, "method_sys_login exec, [4]========[delMyUsingPropsForOutTime end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))
        
        #---清理过期服装        
        my_goods = tmpUser.m_userinfo.get('my_bodyinfo')
        if my_goods.get('goods'):
            from home import home
            tmp_my_goods =  copy.deepcopy(my_goods)
            home.instance().save_my_bodyinfo(request, tmp_my_goods )
        log.print_debug(logger, "method_sys_login exec, [5]========[save_my_bodyinfo end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))

        #---通知好友上线
        user.UserManager.notice_friends(tmpUser) #上线把我关注的和关注我的保存到缓存
        log.print_debug(logger, "method_sys_login exec, [6]========[notice_friends end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))

        #---发回应消息
        from bar_order import BarOrderManager
        tmpuserInfo = BarOrderManager.instance().getUserInfoToClientForLogin(tmpUser) #从内存获取用户信息
        print "@wudi@>tmpuserInfo>", tmpuserInfo
        tmpSendMsgUtil.add_item("user", tmpuserInfo)
        tmpSendMsgUtil.add_item("systime", int(time.time()))   #当前系统时间
        
        if not tmpUser.isRegFinish(): #(未走完注册流程, 发送剩余步骤及其它信息)
            tmpConfigRegSexLeftInfo = const.Config_sys_register_sex_left_info()
            tmpSendMsgUtil.add_item("reg_sex_left_info", tmpConfigRegSexLeftInfo)   #注册性别左侧滚动信息
        
        tmpSendMsgUtil.send(cmd) #发送--
        log.print_debug(logger, "method_sys_login exec, [7]========[send to client end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))

        #---给用户push登陆系统信息
        user.UserManager.push_user_login_info(tmpUser)        
        log.print_debug(logger, "method_sys_login exec, [8]========[push_user_login_info end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))

        #---给用户push首页滚动消息
        user.UserManager.push_sys_info_homepage_msg(tmpUser)
        log.print_debug(logger, "method_sys_login exec, [9]========[push_sys_info_homepage_msg end], socket_id:[%s], data:%s, time[%s]" % (socket_id, data, time.time()))

        #----通知php, 用户上线，写登陆信息到用户被关注的人员的文本
        user.UserManager.sendLogFriendInfoUrl(uid, tmpUser.getNickname(), cmd)
    else:
        tmpSendMsgUtil.update_res("user_is_null")
        tmpSendMsgUtil.send(cmd)    
    
def method_sys_register_name(request, data):
    '''注册用户名和密码'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_sys_register_name exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = 'sys_register_name'
    
    data_dict = util.jsonDecode(data)
    tmpReqName = data_dict.get("name")
    tmpReqPwd = data_dict.get("pwd")
       
    conn = mysql()
    sql = "SELECT uid,nickname FROM t_user WHERE name = '%s'" %  conn.escape_string(tmpReqName)
    row = conn.getRow(sql)
    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    if row:              
        tmpSendMsgUtil.update_res("exit_user")     
        tmpSendMsgUtil.send(cmd)
        return
        
    tmpConfigRegStep = const.Config_Reg_Step_List  #配置文件获取注册步骤 
    
    #---插入用户表, 数据表， 记录表
    strData = {}
    strData['regtime'] = time.strftime('%Y-%m-%d %H:%M:%S') #注册时间
    strData['reg_step'] = json_encode(tmpConfigRegStep)
    strData['name'] = tmpReqName            #用户名
    strData['pwd'] = tmpReqPwd              #密码    
    
    #---插入新用户到DB
    uid = conn.inData(table="t_user", data=strData, insert_id=1)
    tmpLevel = 1
    tmpEnergy = util.ConfigManager.getEnergyByLevel(tmpLevel) #人缘
    #20120229新增
    
    tmpEloquence = util.ConfigManager.getEloquenceByLevel(tmpLevel) #人缘
    tmpKnowledge = util.ConfigManager.getKnowledgeByLevel(tmpLevel) #人缘
    tmpConstitution = util.ConfigManager.getConstitutionByLevel(tmpLevel) #人缘
    tmpMood = util.ConfigManager.getMoodByLevel(tmpLevel) #人缘
    tmpAppearance = util.ConfigManager.getAppearanceByLevel(tmpLevel) #人缘
    
    conn.inData(table="t_user_data", data={"uid":uid,
                                            "level":1,
                                             "energy":tmpEnergy,
                                             "eloquence":tmpEloquence,
                                             "knowledge":tmpKnowledge,
                                             "constitution":tmpConstitution,
                                             "mood":tmpMood,
                                             "appearance":tmpAppearance
                                             }, insert_id=None)        
    conn.inData(table="t_user_record", data={"uid":uid,"last_clean":strData['regtime'],"clean":const.Config_clean_max()}, insert_id=None)  
                
    #---更新缓存, 用户不存在， 则把用户添加到在线用户队列
    userinfo = user.UserManager.get_userinfo(uid, False) #DB获取用户信息
    if not user.UserManager.update_user(uid=uid, userinfo=userinfo):
        user.UserManager.add_user(userinfo, request)
        
    #---发送消息---
    tmpSendMsgUtil.add_item("user", {"uid":uid, "reg_step": tmpConfigRegStep})
    tmpSendMsgUtil.add_item("systime", int(time.time()))   #当前系统时间 
    tmpConfigRegSexLeftInfo = const.Config_sys_register_sex_left_info()
    tmpSendMsgUtil.add_item("reg_sex_left_info", tmpConfigRegSexLeftInfo)  #注册性别时左侧滚动信息
    tmpSendMsgUtil.send(cmd) 
    

def method_sys_register_sex(request, data):
    '''注册昵称和性别'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_sys_register_sex exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "sys_register_sex"    
     
    #data_dict = json_decode(data.decode('latin-1').encode('utf-8'))
    data_dict = util.jsonDecode(data)
    tmpReqSex = int(data_dict.get('sex'))         
    #tmpReqNickname2 = data_dict.get('nickname').encode('utf-8')
    tmpReqNickname = data_dict.get('nickname')
 
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
    
    tmpUserRegStep = tmpOwnerUser.getUserInfoToList("reg_step")       #缓存获取用户注册步骤
    #删除步骤, 返回True表示删除成功即第一次走此步骤, False表示步骤不存在及已经走过此步骤
    bDelete = util.deleteFromList(tmpUserRegStep, "reg_sex")        
     
    uid = tmpOwnerUser.getUID()
    strWhere = "WHERE uid = '%d'" % uid 
    
    #---更新用户表昵称,性别,注册步骤    
    strData = {}
    strData['reg_step'] = json_encode(tmpUserRegStep)   #注册步骤
    strData['sex'] = tmpReqSex                          #性别
    strData['nickname'] = tmpReqNickname                #昵称
    
    conn = mysql()
    conn.upData(table='t_user', data=strData, where=strWhere)
    
    #---更新数据表及记录表昵称
    strData = {}
    strData['nickname'] = tmpReqNickname    #昵称
    conn.upData(table='t_user_data', data=strData, where=strWhere)
    conn.upData(table='t_user_record', data=strData, where=strWhere)
        
    #---查询DB, 然后更新缓存 
    tmpUserInfo = user.UserManager.get_user_basic_info(uid, "sex, nickname") #重新查询DB     
    tmpOwnerUser.setUserInfo("sex", tmpUserInfo.get("sex"))
    tmpOwnerUser.setUserInfo("nickname", tmpUserInfo.get("nickname"))
    
    #---发送消息---
    tmpSendMsgUtil.send(cmd)
    
    #---数值变化
    if bDelete:  #True表示删除成功即第一次走此步骤
        util.CountUserUtil.judgeAndEditExt(cmd, request, uid, "reg_step_reg_sex", bJudge=False)
    
    #---push用户登录信息及首页滚动信息
    user.UserManager.push_user_login_info(tmpOwnerUser)
    user.UserManager.push_sys_info_homepage_msg(tmpOwnerUser)
        
#    #--注册赠送礼物[注: 已修改为第一购买成功商品 赠送注册礼物]  
#    tmpGoodsList = const.Config_reg_send_goods_to_boy()  #从配置文件取得对应的赠送商品列表
#    if tmpOwnerUser.getSex()==0:
#        tmpGoodsList = const.Config_reg_send_goods_to_girl() 
#    store.send_goods_to_somebody(tmpOwnerUser, tmpGoodsList)#送礼, 修改缓存, 修改DB
    
def method_sys_edit_user_info(request, data):
    '''修改用户信息'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_sys_edit_user_info exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "sys_edit_user_info"    
     
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #用户不存在
        return    
    
    #data_dict = json_decode(data.decode('latin-1').encode('utf-8'))
    data_dict = util.jsonDecode(data)
    data_dict_user = data_dict.get('user')
    
    if not isinstance(data_dict_user, dict):
        tmpSendMsgUtil.update_res('bad_request')
        tmpSendMsgUtil.send(cmd)
        return None;
       
    tmpReqBirthday = data_dict_user.get('birthday')      #生日
    tmpReqBirthday = tmpReqBirthday[0:10]
    
    tmpReqHeight = data_dict_user.get('height')          #身高
    tmpReqEdu = data_dict_user.get('edu')                #学历
    tmpReqIncome = data_dict_user.get('income')          #收入
    tmpReqProvince = data_dict_user.get('province')      #省
    tmpReqCity = data_dict_user.get('city')              #市
    tmpReqCountry = data_dict_user.get('country')        #县
    tmpReqOtherarea = data_dict_user.get('otherarea')    #其它
    tmpReqNickname = data_dict_user.get('nickname')      #昵称
    
    uid = tmpOwnerUser.getUID() 
    tmpUserRegStep = tmpOwnerUser.getUserInfoToList("reg_step")  #从缓存获取用户注册步骤
    bEditNickname = False  #是否修改了昵称
    
    #判断是否首次注册基本信息
    if not tmpOwnerUser.isRegFinish(): #未走完注册流程
        valMultiple = 0
        tmpCurrentRegStepName = "reg_basic_info"
        bDelete = util.deleteFromList(tmpUserRegStep, tmpCurrentRegStepName)       #删除注册步骤
        if bDelete: #True表示删除成功即第一次走此步骤
            valMultiple = 3   #倍数
            if tmpReqEdu and tmpReqEdu > 0:       #填写学历, 则得数值
                valMultiple += 1
            if tmpReqIncome and tmpReqIncome > 0: #填写收入, 则得数值
                valMultiple += 1
        else: #重新填写未填项目
            if tmpReqEdu and tmpReqEdu >0 and tmpOwnerUser.getUserInfoToInt("edu") == 0:#学历
                valMultiple += 1
            if tmpReqIncome and tmpReqIncome > 0 and tmpOwnerUser.getUserInfoToInt("income") == 0:#收入
                valMultiple += 1 
        if valMultiple > 0:
            tmpLogicMapObj = ConfigManager.getLogicInfo("reg_step_reg_basic_info")       #获取配置项
            util.ConfigManager.setLogicInfoExt(tmpLogicMapObj, valMultiple)              #修改配置项 , 每项乘倍数 (参数, 倍数)''' 
            util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj, False) #数值变化
    else:
        valMultiple = 0   #倍数
         
#        if tmpReqNickname != tmpOwnerUser.getNickname():
#            bEditNickname = True
#            valMultiple += 1
    
        if tmpReqBirthday != tmpOwnerUser.getBirthday():#生日
            valMultiple += 1
        if tmpReqHeight != tmpOwnerUser.getUserInfo("height"):#身高
            valMultiple += 1
        
        if tmpReqProvince != tmpOwnerUser.getUserInfo("province"):#地区-省
            valMultiple += 1
        elif tmpReqCity != tmpOwnerUser.getUserInfo("city"):#地区-市
            valMultiple += 1
        elif tmpReqCountry != tmpOwnerUser.getUserInfo("country"):#地区-县
            valMultiple += 1
            
        if tmpReqEdu != tmpOwnerUser.getUserInfoToInt("edu"):#学历
            valMultiple += 1
        if tmpReqIncome != tmpOwnerUser.getUserInfoToInt("income"):#收入
            valMultiple += 1 
            
        tmpLogicMapObj = ConfigManager.getLogicInfo("edit_basic_info")    #获取配置项
        util.ConfigManager.setLogicInfoExt(tmpLogicMapObj, valMultiple)   #修改配置项 , 每项乘倍数 (参数, 倍数)''' 
        if not util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj):
            return  #非首次注册，则判断数值是否扣除成功
    
    #---更新用户表    
    strWhere = "WHERE uid = '%d'" % uid
    strData = {}
    strData['reg_step'] = json_encode(tmpUserRegStep)   #注册步骤
    strData['birthday'] = tmpReqBirthday      #生日
    strData['height'] = tmpReqHeight          #身高
    strData['edu'] = tmpReqEdu                #学历
    strData['income'] = tmpReqIncome          #身高
    strData['province'] =tmpReqProvince       #省
    strData['city'] = tmpReqCity              #市
    strData['country'] = tmpReqCountry        #县
    strData['otherarea'] = tmpReqOtherarea    #其它
    if bEditNickname: #如果修改了昵称
        strData['nickname'] = tmpReqNickname
    
    conn = mysql()
    conn.upData(table='t_user', data=strData, where=strWhere)
    
    if bEditNickname: #修改了昵称, 修改其它两个用户表
        strData2 = {}
        strData2['nickname'] = tmpReqNickname
        conn.upData(table='t_user_data', data=strData2, where=strWhere)
        conn.upData(table='t_user_record', data=strData2, where=strWhere)
           
    #---查询DB, 然后更新缓存 
    tmpUserInfo = user.UserManager.get_user_basic_info(uid) #重新查询DB 
    if tmpUserInfo:
        tmpArray = ["nickname", "birthday", "height", "edu", "income", "province", "city", "country", "otherarea", "age"]
        for tmpName in tmpArray:
            tmpOwnerUser.setUserInfo(tmpName, tmpUserInfo.get(tmpName))
           
    #---发送消息---
    tmpSendMsgUtil.send(cmd)

def method_query_user_info(request, data):
    '''查询用户信息'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_query_user_info exec, socket_id:[%s], data:%s" % (socket_id, data))
    cmd = "query_user_info"
    
    data_dict = json_decode(data)
    tmpReqType = data_dict.get('type')                     #请求类型
    tmpReqUID = data_dict.get('uid')                       #被请求者UID
    tmpReqClientAdditon = data_dict.get("client_addition") #客户端附加信息
    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
       
    if tmpReqType not in [0, 1, 2, 3, 4]:              
        tmpSendMsgUtil.update_res("bad_request")      #参数错误
        tmpSendMsgUtil.send(cmd)
        return
        
    if tmpReqType == 0:
        userinfo = user.UserManager.get_userinfo(tmpReqUID)
    elif tmpReqType == 1:
        userinfo = user.UserManager.get_user_game_info(tmpReqUID)
    elif tmpReqType == 2:
        userinfo = user.UserManager.get_user_basic_info(tmpReqUID)
    elif tmpReqType == 3:
        userinfo = user.UserManager.get_user_wear_info(tmpReqUID, 'uid,my_bodyinfo')
        if(userinfo['my_bodyinfo']):
             userinfo['my_bodyinfo'] = json_decode(userinfo['my_bodyinfo'])
    elif tmpReqType == 4:
        userinfo = user.UserManager.get_user_wear_info(tmpReqUID)
         
    tmpSendMsgUtil.add_item("user", userinfo)
    tmpSendMsgUtil.add_item("type", tmpReqType)    
    tmpSendMsgUtil.add_item("client_addition", tmpReqClientAdditon) #客户端附加信息
    tmpSendMsgUtil.send(cmd)
    
##关注用户A关注B
#def method_set_attention(request, data):
#    socket_id = request.socket_id
#    cmd = 'set_attention' 
#    log.print_debug(logger, "method_set_attention exec, socket_id:[%s], data:%s" % (socket_id, data))
#    
#    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
#    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
#    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
#        return
#        
#    data_dict = json_decode(data) 
#    to_uid = data_dict.get('uid')
#    tmpClientAdditon = data_dict.get("client_addition")#客户端附加信息
#    if not tmpClientAdditon:
#        tmpClientAdditon = "" 
#        
#    tmpTargetUser = UserManager.getUserByUIDExt(cmd, tmpSendMsgUtil, to_uid);     
#    if tmpTargetUser is None: #目标对象不存在， 则发错误消息
#        return 
#        
#    #主动者数值变化-----
#    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), "Config_Attention"):
#        return
#    
#    #{"123456": {'nickname': 'kaka', 'uid': 123465}, "456789": {'nickname': 'aaa', 'uid': 456789}}
#    res = user.UserManager.set_user_attention(request, to_uid)    
#    if res["res"] != True:        
#        tmpSendMsgUtil.update_res(res['res'])
#    else:
#        tmpSendMsgUtil.add_item("type", res['type'])
#        tmpSendMsgUtil.add_item("user", res['user'])
#        
#        tmpOwnerUser.insertMyAtttList(to_uid)                  #加入"我关注的"列表 
#        tmpTargetUser.insertAtttMeMap(tmpOwnerUser.getUID())  #把我的uid加入对方"关注我的"列表
#            
#        UserManager.updateUserCount('count_atted', 1, to_uid)#增加统计数量
#        
#        #被动者数值变化--[被关注多少次加魅力]----
#        tmpLimit = const.Config_Attention_get_charm_limit()
#        if not tmpLimit:
#            tmpLimit = 1
#        tmpCount = tmpTargetUser.getUserInfoToInt("count_atted")
#        if tmpCount > 0 and (tmpCount%tmpLimit) == 0:
#            tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
#            ConfigManager.setLogicInfoVal_Charm(tmpLogicMapObj, 1)       #魅力增减
#            util.CountUserUtil.judgeAndEditExt(cmd, request, to_uid, tmpLogicMapObj, False)
#    
#    tmpSendMsgUtil.add_item("client_addition", tmpClientAdditon) #客户端附加信息
#    tmpSendMsgUtil.send(cmd)

#关注用户A关注B
def method_set_attention(request, data):
    socket_id = request.socket_id
    cmd = 'set_attention' 
    log.print_debug(logger, "method_set_attention exec, socket_id:[%s], data:%s" % (socket_id, data))

    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
       
    data_dict = json_decode(data) 
    tmpReqUID = data_dict.get('uid')                    #被关注者UID
    tmpClientAdditon = data_dict.get("client_addition") #客户端附加信息
    if not tmpClientAdditon:
        tmpClientAdditon = ""
        
    ownerUID = tmpOwnerUser.getUID()
    ownerSex = tmpOwnerUser.getSex()
        
    bTargetUserOnline, tmpTargetUser = user.UserManager.getUserObjByUID(tmpReqUID) #用户对象  
    if tmpTargetUser is None:
        log.print_warning(logger, "method_set_attention exec, tmpReqUID:[%s] is null" % tmpReqUID) 
        tmpSendMsgUtil.update_res("user_is_null")     
        tmpSendMsgUtil.send(cmd) 
        return
    
    if ownerUID == tmpReqUID: #不能关注自己 
        tmpSendMsgUtil.update_res("is_attention_myself");
        tmpSendMsgUtil.send(cmd)
        return
    
    if ownerSex == tmpTargetUser.getSex(): #不能关注同性
        tmpSendMsgUtil.update_res("is_attention_same_sex");
        tmpSendMsgUtil.send(cmd)
        return
        
    if tmpOwnerUser.isInMyAtttListUID(tmpReqUID): #已关注了对方
        tmpSendMsgUtil.update_res("had_attention_user");
        tmpSendMsgUtil.send(cmd)
        return
        
    tmpJudgeConfigLogicName = "Config_Attention"
    #主动者判断数值是否足够
    if not util.CountUserUtil.judgeUserGameValueEnoughExt(cmd, request, ownerUID, tmpJudgeConfigLogicName):
        return
 
     #把B加入A的关注列表
    tmpType = tmpOwnerUser.insertMyAtttMap(tmpTargetUser)  
    #把A加入B的关注我的列表
    tmpTargetUser.insertAtttMeMap(tmpOwnerUser)
    
    #---我的关注， 关注我的，我的好友-写DB--
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpOwnerUser)
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpTargetUser)
    
    UserManager.updateUserCount('count_att', 1, ownerUID)      #增加统计数量; 我关注的数量
    UserManager.updateUserCount('count_atted', 1, tmpReqUID)   #增加统计数量: 被关注的数量
    
    tmpSendMsgUtil.add_item("type", tmpType)                        #0: 单方关注, 1: 双方关注
    tmpSendMsgUtil.add_item("client_addition", tmpClientAdditon)    #客户端附加信息
    tmpSendMsgUtil.send(cmd)
    
    if bTargetUserOnline == 1:
        #发一条系统消息通知对方B
        tmpSendType = "add_attention"
        tmpContent = "%s关注了你" % tmpOwnerUser.getNickname()
        tmpContentAddtion = UserManager.createDBFriendItem(tmpOwnerUser, "attt_me")  #构建格式  {uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
        UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, tmpReqUID)  
    
    #发一条系统消息通知B
    tmpSendType = "add_attention"
    tmpContent = "你关注了%s" % tmpTargetUser.getNickname()
    tmpContentAddtion = UserManager.createDBFriendItem(tmpTargetUser, "my_attt", bTargetUserOnline)  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
    UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, ownerUID)  

    #主动者数值变化----
    util.CountUserUtil.judgeAndEditExt(cmd, request, ownerUID, tmpJudgeConfigLogicName, bJudge=False)
        
    #被动者数值变化--[被关注多少次加一点魅力]----
    tmpLimit = const.Config_Attention_get_charm_limit()
    if not tmpLimit:
        tmpLimit = 1
    tmpCount = tmpTargetUser.getUserInfoToInt("count_atted") #被关注数量
    if tmpCount > 0 and (tmpCount%tmpLimit) == 0:
        tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
        ConfigManager.setLogicInfoVal_Charm(tmpLogicMapObj, 1)       #魅力增减
        util.CountUserUtil.judgeAndEditExt(cmd, request, tmpReqUID, tmpLogicMapObj, False)    
    
    import task#添加成功则执行任务
    task.taskManager.do_task(tmpOwnerUser,'main_task','add_friend',tmpReqUID)
    task.taskManager.do_task(tmpOwnerUser,'first','first_add_friend',tmpReqUID)

#删除好友或者被关注的用户
def method_delete_attention_friend(request, data):
    socket_id = request.socket_id
    cmd = 'delete_attention_friend' 
    log.print_debug(logger, "method_delete_attention_friend exec, socket_id:[%s], data:%s" % (socket_id, data))
    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return

    data_dict = json_decode(data) 
    tmpReqUID = data_dict.get('uid')   #被删除者UID
    ownerUID = tmpOwnerUser.getUID()
    if ownerUID == tmpReqUID: #不能删除自己 
        tmpSendMsgUtil.update_res("is_delete_attention_myself");
        tmpSendMsgUtil.send(cmd)
        return
    
    tmpSendMsgUtil.add_item("uid", tmpReqUID) #被删除者

    tmpFriendRelation = tmpOwnerUser.isInMyListExt(tmpReqUID)
    if tmpFriendRelation is None: #被删除者  不在 "我的关注,被关注, 暗恋, 被暗恋列表"
        #tmpSendMsgUtil.update_res("attention_not_my_list");
        tmpSendMsgUtil.send(cmd) #直接发成功
        return
    
    tmpRelationRange = ["my_attt", "my_hidden_love"]  #用户只有删除 我的关注， 我的暗恋, 才有数值变化
    tmpJudgeConfigLogicName = "Config_Attention_delete"
    if tmpFriendRelation in tmpRelationRange:
        if tmpFriendRelation in ["my_hidden_love"]:
            tmpJudgeConfigLogicName = "Config_hidden_love_delete"
        #主动者判断数值是否足够
        if not util.CountUserUtil.judgeUserGameValueEnoughExt(cmd, request, ownerUID, tmpJudgeConfigLogicName):
            return
    
    #--获取被删除者对象--
    tmpTargetUser = user.UserManager.get_user_by_uid(tmpReqUID)
    if not tmpTargetUser:  #用户不在线
        bInLine = False
        tmpInfo = user.UserManager.get_userinfo_friend_fromDB(tmpReqUID)    #查询DB数据,好友，关注，被关在等
        
        if len(tmpInfo) == 0: #要删除的用户不存在
            log.print_warning(logger, "method_delete_attention_friend exec, tmpReqUID:[%s] is null" % tmpReqUID) 
            tmpSendMsgUtil.update_res("user_is_null")     
            tmpSendMsgUtil.send(cmd) 
            return
        
        tmpTargetUser = user.User(0, tmpInfo, None)            #新建用户
        user.UserManager.setUserFriendMapExt(tmpTargetUser, tmpInfo)#存到内存
#        tmpTargetUser.setMyFriendMap(tmpInfo.get("my_friend")) #把好友信息等转存到用户对象
#        tmpTargetUser.setMyAtttMap(tmpInfo.get("my_attt"))
#        tmpTargetUser.setAtttMeMap(tmpInfo.get("attt_me"))
#        tmpTargetUser.setMyHiddenLoveMap(tmpInfo.get("my_hidden_love"))
#        tmpTargetUser.setHiddenLoveMeMap(tmpInfo.get("hidden_love_me"))
    
    #把B从A的多个列表中删除
    tmpOwnerUser.delMyFriendExt(tmpReqUID)    
    #把A从B的多个列表中删除
    tmpTargetUser.delMyFriendExt(ownerUID)
    
    #---我的关注， 关注我的，我的好友-写DB--
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpOwnerUser)
    UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpTargetUser) 
    
    tmpSendMsgUtil.send(cmd)
    
    #主动者数值变化-----
    if tmpFriendRelation in tmpRelationRange:
        util.CountUserUtil.judgeAndEditExt(cmd, request, ownerUID, tmpJudgeConfigLogicName, bJudge=False)


#把用户拖入黑名单
def method_delete_to_black_list(request, data):
    cmd = 'delete_to_black_list'
    data = json_decode(data)
    if not user.UserManager.check_get_data(request, cmd, data):
        return None
    tmpSendMsgUtil = util.SendMsgUtil(request)
    to_uid = data['uid']    
    res = user.UserManager.set_to_black_list(request, to_uid)
    
    tmpSendMsgUtil.send(cmd)
    

#查询用户好友,关注, 被关注列表    
def method_get_attention_list(request,data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_get_record exec, socket_id:[%s], data:%s" % (socket_id, data))
    cmd = "get_attention_list"
    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #更新好友列表，在线用户状态( 如在线，等级，昵称等)
    tmpMyFriend = {} #user.UserManager.updateFriendOnlineInfo(tmpOwnerUser.getMyFriendMap())
    tmpMyAttt = user.UserManager.updateFriendOnlineInfo(tmpOwnerUser.getMyAtttMap())
    tmpAtttMe = user.UserManager.updateFriendOnlineInfo(tmpOwnerUser.getAtttMeMap())
    tmpMyHiddenLove = user.UserManager.updateFriendOnlineInfo(tmpOwnerUser.getMyHiddenLoveMap())
    tmpHiddenLoveMe = user.UserManager.updateFriendOnlineInfo(tmpOwnerUser.getHiddenLoveMeMap())
    
    tmpSendMsgUtil.add_item("my_friend", tmpMyFriend)
    tmpSendMsgUtil.add_item("my_attt", tmpMyAttt)
    tmpSendMsgUtil.add_item("attt_me", tmpAtttMe)
    tmpSendMsgUtil.add_item("my_hidden_love", tmpMyHiddenLove)
    tmpSendMsgUtil.add_item("hidden_love_me", tmpHiddenLoveMe)
     
    tmpMyAtttSize = tmpOwnerUser.getMyFriendListSize() 
    tmpHiddenLoveMeSize = tmpOwnerUser.getHiddenLoveMeListSize()
    tmpSendMsgUtil.add_item("my_friend_size", tmpMyAtttSize) #我的关注数量
    tmpSendMsgUtil.add_item("hidden_love_me_size", tmpHiddenLoveMeSize)  #粉丝数, 暗恋我的人 
    
    tmpSendMsgUtil.send(cmd)

    
def method_login_get_gift(request, data):
    '''用户领取礼包'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_login_get_gift exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "login_get_gift"
    
    data_dict = json_decode(data)
    tmpReqType = data_dict.get('type')              #领取类型
        
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
       
    #---参数错误
    if tmpReqType not in ["get_yellow_reg_gift", "get_yellow_day_gift", "see_yellow_gift", "get_day_gift"]:
        tmpSendMsgUtil.update_res("bad_request") 
        tmpSendMsgUtil.send(cmd)
        return
    #---非黄钻用户, 不能领取黄钻用户礼包
    if tmpReqType in ["get_yellow_reg_gift", "get_yellow_day_gift"]: 
        if not tmpOwnerUser.isYellow():      
            tmpSendMsgUtil.update_res("not_yellow_user")
            tmpSendMsgUtil.send(cmd)
            return
    #---已经领取或查看, 则错误码返回     
    if tmpOwnerUser.getUserInfoToInt(tmpReqType) == 1:  
        error_code = "login_gift_has_get"
        if tmpReqType in ["get_day_gift"]:
            error_code = "login_gift_has_see" 
        tmpSendMsgUtil.update_res(error_code)
        tmpSendMsgUtil.send(cmd)
        return
    
    if tmpReqType in ["get_yellow_reg_gift", "get_yellow_day_gift", "get_day_gift"]:
        tmpInfo = ""       #信息文字
        tmpGold = 0        #赠送的金币
        tmpGoodsList = []  #赠送的商品列表
         
        if tmpReqType == "get_yellow_reg_gift":    # 黄钻新手注册礼包
            tmpInfo, tmpGold, tmpGoodsList = UserManager.get_config_user_login_info(tmpOwnerUser, "yellow_reg") 
        elif tmpReqType == "get_yellow_day_gift":  # 黄钻每日礼包 
            tmpInfo, tmpGold, tmpGoodsList = UserManager.get_config_user_login_info(tmpOwnerUser, "yellow_day")  
        elif tmpReqType == "get_day_gift":         # 当日首次礼包
            tmpInfo, tmpGold, tmpGoodsList = UserManager.get_config_user_login_info(tmpOwnerUser, "day")
           
        #---送礼, 修改我的商品信息缓存, 修改DB
        store.send_goods_to_somebody(tmpOwnerUser, tmpGoodsList)
        
        #---数值变化
        tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
        ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpGold)     #金币 
        util.CountUserUtil.judgeAndEditExt(cmd, tmpOwnerUser.getRequest(), tmpOwnerUser.getUID(), tmpLogicMapObj, False)
    
    #---修改DB, 是否领取字段
    upData = {}
    upData[tmpReqType] = 1
    conn = mysql()
    conn.upData('t_user_data', upData, "WHERE uid = %d" % tmpOwnerUser.getUID())

    tmpOwnerUser.setUserInfo(tmpReqType, 1) #修改缓存
    #发送成功回应
    tmpSendMsgUtil.send(cmd)
    
    
def method_edit_reg_step(request, data):
    '''修改用户注册步骤'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_edit_reg_step exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "edit_reg_step"
    
    data_dict = json_decode(data)
    print 11111111111111111111111111111111111111111111111
    print data_dict
    tmpReqType = data_dict.get('type')              #领取类型
        
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
     
    tmpRegStepList = const.Config_Reg_Step_List   #配置文件获取注册步骤
    #---参数错误
    if tmpReqType not in tmpRegStepList:
        tmpSendMsgUtil.update_res("bad_request") 
        tmpSendMsgUtil.send(cmd)
        return
     
    tmpUserRegStep = tmpOwnerUser.getUserInfoToList("reg_step") #从缓存获取用户步骤    
    if tmpReqType in tmpRegStepList:#升级到2|3|4级 
        tmpMyAddexp = 0
        tmpMyAddgold=0
        if tmpReqType=='first_up_head' :  
            tmpMyAddexp = 5          
            if tmpOwnerUser.m_userinfo.get('is_upload_head'):               
                tmpMyAddgold = 100
        if tmpReqType=='first_buy_goods' :
            tmpMyAddexp = 15
            tmpMyAddgold = 100
        if tmpReqType=='first_get_my_home_gold' :
            tmpMyAddexp = 30            
            
        tmpMyLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")
        if tmpMyAddgold:                         
            util.ConfigManager.setLogicInfoVal_Gold(tmpMyLogicMapObj, tmpMyAddgold)       
        if tmpMyAddexp:                         
            util.ConfigManager.setLogicInfoVal_Exp(tmpMyLogicMapObj, tmpMyAddexp)
        
        if tmpMyAddexp>0 or tmpMyAddgold>0:
            util.CountUserUtil.judgeAndEditExt('edit_reg_step', request, tmpOwnerUser.getUID(), tmpMyLogicMapObj)          #加钱加经验 
            
    
    util.deleteFromList(tmpUserRegStep, tmpReqType)       #删除步骤
     
    #---修改DB, 是否领取字段
    upData = {}
    upData["reg_step"] = json_encode(tmpUserRegStep)
    conn = mysql()
    conn.upData('t_user', upData, "WHERE uid = %d" % tmpOwnerUser.getUID()) 
    
    #发送成功回应
    tmpSendMsgUtil.send(cmd)

def method_edit_autoinfo(request, data):
    '''设置用户个人特征信息，用于撮合'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_edit_autoinfo exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "edit_autoinfo"
    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None:#当前用户对象不存在， 则发错误消息
        return

    data_dict = util.jsonDecode(data)
    if not isinstance(data_dict, dict):
        tmpSendMsgUtil.update_res('bad_request')
        tmpSendMsgUtil.send(cmd)
        return;
        
    uid = tmpOwnerUser.getUID()
    valMultiple = 0
    tmpAutoinfo = tmpOwnerUser.getAutoInfo()

    util.deleteFromDict(data_dict, "uid")
    util.deleteFromDict(data_dict, "my_uid")

    util.deleteFromDict(tmpAutoinfo, "uid")
    util.deleteFromDict(tmpAutoinfo, "my_uid")

    for k,v in data_dict.iteritems():
        tmpMyVal = tmpAutoinfo.get(k)
        if tmpMyVal and tmpMyVal != v:
            valMultiple += 1
            
    if valMultiple > 0:
        tmpLogicMapObj = ConfigManager.getLogicInfo("edit_edit_autoinfo") #获取配置项
        util.ConfigManager.setLogicInfoExt(tmpLogicMapObj, valMultiple)   #修改配置项 , 每项乘倍数 (参数, 倍数)''' 
        if not util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj):
            return  #非首次注册，则判断数值是否扣除成功

    #tmpAutoinfo.clear() #先清空
    for k,v in data_dict.iteritems():
        tmpAutoinfo[k] = str(v).strip()     
    user.UserManager.update_user(uid, {'autoinfo':tmpAutoinfo})    #更新缓存数据
    
    #---更新DB
    conn = mysql()
    conn.upData('t_user', {'autoinfo':json_encode(tmpAutoinfo)}, "WHERE uid = %d" % uid) 
    tmpSendMsgUtil.send(cmd)
    
def method_get_autoinfo(request,data):
    '''获取用户个人特征信息'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_edit_autoinfo exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "get_autoinfo"
    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    data_dict = json_decode(data)
    uid = data_dict.get('uid');
    if not uid: 
        tmpSendMsgUtil.update_res('bad_request')
        tmpSendMsgUtil.send(cmd)
        return

    tmpOwnerUser = UserManager.get_user_by_uid(uid);
    if tmpOwnerUser:
        tmpAutoinfo = tmpOwnerUser.getAutoInfo()
    else:
        tmpUserInfo = UserManager.get_user_basic_info(uid, 'autoinfo');#不在线，则查DB 
        tmpOwnerUser = user.User(0, tmpUserInfo, None)
            
    tmpAutoinfo = {}
    if tmpOwnerUser:
        tmpAutoinfo = tmpOwnerUser.getAutoInfo()
    
    util.deleteFromDict(tmpAutoinfo, "province")
    util.deleteFromDict(tmpAutoinfo, "city")
    util.deleteFromDict(tmpAutoinfo, "age")
    
    tmpSendMsgUtil.add_item("autoinfo", tmpAutoinfo)
    tmpSendMsgUtil.send(cmd)
    
def method_add_user_data(request,data):
    '''增加用户属性'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_add_user_data exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "add_user_data"
    tmpSendMsgUtil = util.SendMsgUtil(request)    
    data_dict = json_decode(data)
    tmpUid = data_dict.get("uid")#uid
    tmpCol = data_dict.get("col")#需要增加字段数值的名称
    tmpAdd = data_dict.get("add")#增加的值
    tmpTargetUid = data_dict.get("touid")#相关用户uid

    tmpOwnerUser = UserManager.get_user_by_uid(tmpUid)
    if tmpOwnerUser:
        if tmpCol in ["gold","money","exp","courage","quality","energy","charm"]:#修改数值后需通知客户端的字段
            #---数值变化
            tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项    
            
            ConfigManager.setLogicInfoVal(tmpLogicMapObj, tmpCol, tmpAdd)
            if not util.CountUserUtil.judgeAndEditExt(cmd, tmpOwnerUser.getRequest(), tmpUid, tmpLogicMapObj, True):
                tmpSendMsgUtil.update_res('bad_request')
                tmpSendMsgUtil.send(cmd)
                return
            
        else:
            user.UserManager.update_user(tmpUid, {tmpCol:tmpAdd},True)
            conn = mysql()
            conn.upData('t_user_data', {tmpCol:tmpAdd},"WHERE uid = %d" % tmpUid, True) 
    else:        
        #---更新DB        
        conn = mysql()
        conn.upData('t_user_data', {tmpCol:tmpAdd},"WHERE uid = %d" % tmpUid, True) 
    tmpSendMsgUtil.send(cmd)
    
    if tmpCol =='count_invite' and tmpTargetUid:        
        import task#添加成功则执行任务        
        if tmpOwnerUser:            
            task.taskManager.do_task(tmpOwnerUser,'main_task','invite_friend',tmpTargetUid)
        else:#如果邀请人不在线，则执行离线任务
            task.taskManager.do_leave_task(tmpUid,'main_task','invite_friend',tmpTargetUid)
    
def method_talk(request,data):
    ''''发送聊天消息'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_add_user_data exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "talk"
    tmpSendMsgUtil = util.SendMsgUtil(request)   
     
    data_dict = json_decode(data)
    tmpToUid = data_dict.get("uid")      #聊天对方uid
    tmpType = data_dict.get("type")      #发送类型，current 当前模块所有人，private 私聊  horn大喇叭
    tmpContent = data_dict.get("content")#聊天内容
    if len(tmpContent)>90:#30个中文汉字限制
        return
    tmpUser = UserManager.get_user_by_request(request)
    tmpUid = tmpUser.getUID()
    tmpToUser = UserManager.get_user_by_uid(tmpToUid)
    
    tmpToUserDict={}
    if tmpToUser:
        tmpToUserDict = {"uid":tmpToUser.getUID(),"sex":tmpToUser.getSex(),"nickname":tmpToUser.getNickname()}
    if not tmpUser:
        return
    tmpTime = int(time.time())
    
    if tmpType!='horn':
        if tmpTime - tmpUser.m_last_talk<3:#聊天时间间隔 （秒）        
            return
        
    tmpUser.m_last_talk = int(time.time())
    
    tmpUserDict = {"uid":tmpUid,"sex":tmpUser.getSex(),"nickname":tmpUser.getNickname()}
    
    if tmpUser.getSex()==1:
        tmpSexColor = '#337fe5'
        tmpUserColor='#f2f688'
        tmpSexStr = '♂'
        if tmpType=='horn':
            tmpMsgColor = '#ff8800'
        else:
            tmpMsgColor = '#ffffff'    
       
    else:
        tmpSexColor = '#FF00E4'
        tmpUserColor='#f2f688'
        tmpSexStr = '♀'
        if tmpType=='horn':
            tmpMsgColor = '#ff8800'
        else:
            tmpMsgColor = '#ffffff'        
    
    tmpContent = '<font color="%s">%s</font> <font color="%s"><u><a href="event:%s">%s</a></u></font>: <font color="%s">%s</font>'%(tmpSexColor,tmpSexStr,tmpUserColor,tmpUid,
                                                                                                                 tmpUser.getNickname(),tmpMsgColor,tmpContent)
       
    tmpSendMsgUtil.add_item("type", tmpType)
    tmpSendMsgUtil.add_item("content", tmpContent)
    tmpSendMsgUtil.add_item("user", tmpUserDict)
    tmpSendMsgUtil.add_item("touser",tmpToUserDict)
    tmpContent = tmpSendMsgUtil.getEncodeContent() #编码      
    
    if tmpType=='horn':        
        if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpUid, 'horn_talk'):
            return 
        UserManager.sendMsgToAll(cmd, msg=tmpContent)   #给系统所有人发消息           
        return
     
    if tmpType=='private':
        tmpSendMsgUtil.send(cmd=cmd, request=tmpUser.m_request, msg=tmpContent)
        tmpSendMsgUtil.send(cmd=cmd, request=tmpToUser.m_request, msg=tmpContent)
        return
        
    if tmpType=='current':    
        tmpPlace = tmpUser.getCurrentPlace()
        tmpAllUser = UserManager.s_map_user       
        for k,v in tmpAllUser.items():
            if v:
                if v.getCurrentPlace()== tmpPlace:               
                    tmpSendMsgUtil.send(cmd=cmd, request=v.m_request, msg=tmpContent)
        return

#----注册方法---------
util.registMethod("sys_login", method_sys_login)                              #用户登录
util.registMethod("sys_register_name", method_sys_register_name)              #用户名注册
util.registMethod("sys_register_sex", method_sys_register_sex)                #用户昵称性别注册
util.registMethod("sys_edit_user_info", method_sys_edit_user_info)            #用户编辑基本资料
util.registMethod("query_user_info", method_query_user_info)                  #查询用户信息
util.registMethod("set_attention", method_set_attention)                      #设置关注  加好友
#util.registMethod("get_attention", method_get_attention)                     #获取关注好友
util.registMethod("delete_attention_friend", method_delete_attention_friend)  #删除关注 删除好友
util.registMethod("delete_to_black_list", method_delete_to_black_list)        #拖到黑名单
util.registMethod("get_attention_list", method_get_attention_list)            #获取用户好友,关注, 被关注列表
util.registMethod("login_get_gift", method_login_get_gift)                    #用户领取礼包
util.registMethod("edit_reg_step", method_edit_reg_step)                      #用户注册步骤
util.registMethod("edit_autoinfo", method_edit_autoinfo)                      #设置用户个人特征信息，用于撮合
util.registMethod("get_autoinfo", method_get_autoinfo)                        #获取用户个人特征信息，用于撮合

util.registMethod("add_user_data", method_add_user_data)                      #增加用户属性值
util.registMethod("talk", method_talk)                                        #聊天